package com.scwatch.core.web.back;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.scwatch.common.office.ExcelUtil;
import com.scwatch.common.upload.Uploader;
import com.scwatch.common.util.Dates;
import com.scwatch.common.web.Servlets;
import com.scwatch.core.domain.Excel;
import com.scwatch.core.domain.Site;
import com.scwatch.core.support.Context;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * UploadController
 *
 * @author gjl
 *
 */
@Controller
@RequestMapping("/core")
public class UploadController extends UploadControllerAbstract {
    @RequestMapping(value = "upload_image.do", method = RequestMethod.POST)
    public void uploadImage(Boolean scale, Boolean exact, Integer width, Integer height, Boolean thumbnail,String avatarId,
                            Integer thumbnailWidth, Integer thumbnailHeight, Boolean watermark, HttpServletRequest request,
                            HttpServletResponse response) throws IOException {
        Site site = Context.getCurrentSite();
        upload(site, request, response, Uploader.IMAGE, scale, exact, width, height, thumbnail, thumbnailWidth,
                thumbnailHeight, false,avatarId);
    }
    @RequestMapping(value = "ue_upload_image.do", method = RequestMethod.POST)
    public void ue_upload_image(Boolean scale, Boolean exact, Integer width, Integer height, Boolean thumbnail,
                            Integer thumbnailWidth, Integer thumbnailHeight, Boolean watermark, HttpServletRequest request,
                            HttpServletResponse response) throws IOException {
        Site site = Context.getCurrentSite();
        upload(site, request, response, Uploader.IMAGE, scale, exact, width, height, thumbnail, thumbnailWidth,
                thumbnailHeight, watermark,null);
    }

    @RequestMapping(value = "upload_flash.do", method = RequestMethod.POST)
    public void uploadFlash(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Site site = Context.getCurrentSite();
        upload(site, request, response, Uploader.FLASH);
    }

    @RequestMapping(value = "upload_file.do", method = RequestMethod.POST)
    public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Site site = Context.getCurrentSite();
        upload(site, request, response, Uploader.FILE);
    }
    /*----------------------------------------[ 上传 节目单 ]-------------------------------*/
    @RequestMapping(value = "upload_file_channel.do", method = RequestMethod.POST)
    public void uploadFileChannel(HttpServletRequest request, HttpServletResponse response/*, @RequestParam(required = false,value="") MultipartFile[] files*/) throws Exception {
        MultipartFile multipartFile = getMultipartFileInfo(request);
        //验证
        ExcelUtil.checkFile(multipartFile);

        Site site = Context.getCurrentSite();
        ImportParams params = new ImportParams();
        params.setHeadRows(1);

        //获取上传的excel文件
        List<Excel> list = ExcelImportUtil.importExcel(multipartFile.getInputStream(), Excel.class,params);
        Map<String, List<Excel>> map = new HashMap<>();
        for (Excel excel : list) {
            List<Excel> excels = map.get(excel.getDate());
            if (excels == null) {
                excels = new ArrayList<>();
            }
            excels.add(excel);
            map.put(excel.getDate(), excels);
        }

        JSONArray jsonArray = new JSONArray();
        for (String key : map.keySet()) {
            List<Excel> excels = map.get(key);
            JSONObject item = new JSONObject();
            item.put("liveProgrammeDate", key);
            JSONArray programmeList = new JSONArray();
            item.put("programmeList", programmeList);
            for (int i = 0; i < excels.size(); i++) {
                Excel excel = excels.get(i);
                JSONObject programme = new JSONObject();
                programme.put("programmeId", i + 1);
                programme.put("programmeTitle", excel.getName());
                Date time = excel.getTime();
                if(time!=null){
//                    programme.put("startTime",  DateUtils.format(time, "HH:mm:ss"));
                    programme.put("startTime", Dates.formatDate(time, "HH:mm:ss"));
                    programmeList.add(programme);
                }

            }
            jsonArray.add(item);
        }

        // 排序
        Collections.sort(jsonArray, new Comparator() {
            public int compare(Object o1, Object o2) {
                JSONObject j1 = (JSONObject) o1;
                JSONObject j2 = (JSONObject) o2;
                String str1=j1.getString("liveProgrammeDate").replaceAll("-","");
                String str2=j2.getString("liveProgrammeDate").replaceAll("-","");
                Integer int1=Integer.valueOf(str1);
                Integer int2=Integer.valueOf(str2);
                return int2-int1;
            }
        });

        //上传并处理返回值
        JSONObject jsonObject = JSONObject.parseObject(uploadForSinatv(site, request, Uploader.FILE));
        if (jsonObject.getBoolean("success")){
            jsonObject.put("programmes",jsonArray.toJSONString());
        }
        System.err.println(jsonObject.toJSONString());
        Servlets.writeHtml(response, jsonObject.toJSONString());
    }

    @RequestMapping(value = "upload_video.do", method = RequestMethod.POST)
    public void uploadVideo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Site site = Context.getCurrentSite();
        upload(site, request, response, Uploader.VIDEO);
    }

    @RequestMapping(value = "upload_doc.do", method = RequestMethod.POST)
    public void uploadDocument(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Site site = Context.getCurrentSite();
        upload(site, request, response, Uploader.DOC);
    }

    @RequestMapping(value = "/ueditor.do")
    public void ueditor(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String action = request.getParameter("action");
        if ("config".equals(action)) {
            super.ueditorConfig(request, response);
        } else if ("uploadimage".equals(action)) {
//            uploadImage(null, null, null, null, null, null, null, null, request, response);
        } else if ("catchimage".equals(action)) {
            ueditorCatchImage(request, response);
        } else if ("uploadvideo".equals(action)) {
            uploadVideo(request, response);
        } else if ("uploadfile".equals(action)) {
            uploadFile(request, response);
        } else if ("uploadscrawl".equals(action)) {

        } else if ("listimage".equals(action)) {

        } else if ("listfile".equals(action)) {

        }else if("ue_upload_image".equals(action)){
            ue_upload_image(null, null, null, null, null, null, null, null, request, response);
        }
    }

    public void ueditorCatchImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Site site = Context.getCurrentSite();
        super.ueditorCatchImage(site, request, response);
    }
}
